const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 产品模型
const productSchema = new Schema({
  name: { type: String, required: true },
  category_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'ProductCategory',
    required: true 
  },
  price: { type: Number, required: true },
  stock: { type: Number, default: 0 },
  description: String,
  images: [String],
  tags: [String],
  sales_count: { type: Number, default: 0 },
  create_time: { type: Date, default: Date.now },
  activities: [{
    type: Schema.Types.ObjectId,
    ref: 'ProductActivity'
  }]
});

// 产品方法
productSchema.statics.getProducts = async function (category_id, offset, limit) {
  try {
    const query = {};
    if (category_id) query.category_id = category_id;
    const total = await this.countDocuments(query);
    const rows = await this.find(query)
        .skip(Number(offset))
        .limit(Number(limit));
    return { rows, total };
  } catch (error) {
    throw error;
  } 
}

// 产品方法
productSchema.statics.createProduct = async function (data) {
  try {
    const product = await this.create(data);
    return product;
  } catch (error) {
    throw error;
  }
}

// 产品方法
productSchema.statics.updateProduct = async function (id, data) {
  try {
    return await this.findByIdAndUpdate(id, data, { new: true });
  } catch (error) {
    throw error;
  }
}

// 产品方法
productSchema.statics.deleteProduct = async function (id) {
  try {
    return await this.findByIdAndDelete(id);
  } catch (error) {
    throw error;
  }
}

// 产品方法
productSchema.statics.updateStatus = async function (id, status) {
  try {
    return await this.findByIdAndUpdate(id, { status }, { new: true });
  } catch (error) {
    throw error;
  }
}

// 产品方法
productSchema.statics.getAnalytics = async function () {
  try {
    const totalProducts = await this.countDocuments();
    const totalSales = await this.aggregate([
      { $unwind: '$activities' },
      { $group: { _id: null, total: { $sum: '$activities.sales_count' } } }
    ]);
    return { totalProducts, totalSales: totalSales[0].total };
  } catch (error) {
    throw error;
  }
}
module.exports = mongoose.model('Product', productSchema);